<template>
  <div>
    <el-card style="height: 85vh;">
      <vxe-split padding :action-config="actionConfig">
        <!-- 左侧主表格 -->
        <vxe-split-pane>
          <vxe-grid
            ref="gridRef"
            v-bind="gridOptions"
            v-on="gridEvents"
            @checkbox-all="selectAllChangeEvent"
            @checkbox-change="selectChangeEvent"
          >
            <template #operate="{ row }">
              <vxe-button
                status="primary"
                mode="text"
                icon="vxe-icon-edit"
                @click="handleEdit(row)"
                content="编辑"
              ></vxe-button>
              <vxe-button
                status="danger"
                mode="text"
                icon="vxe-icon-delete"
                @click="handleDelete(row)"
                content="删除"
              ></vxe-button>
            </template>
          </vxe-grid>
        </vxe-split-pane>

        <!-- 右侧子表格 -->
        <vxe-split-pane>
          <vxe-grid
            ref="doubleGridRef"
            v-bind="doubleGridOptions"
            @checkbox-all="selectAllChangeEvent"
            @checkbox-change="selectChangeEvent"
            @toolbar-button-click="rightToolbarClick"
            @form-submit="rightFormSubmit"
            @form-reset="rightFormReset"
          >
            <template #operate="{ row }">
              <vxe-button
                status="primary"
                mode="text"
                icon="vxe-icon-edit"
                @click="handleRightEdit(row)"
                content="编辑"
              ></vxe-button>
              <vxe-button
                status="danger"
                mode="text"
                icon="vxe-icon-delete"
                @click="handleRightDelete(row)"
                content="删除"
              ></vxe-button>
            </template>
          </vxe-grid>
        </vxe-split-pane>
      </vxe-split>

      <!-- 左侧主表格弹窗 -->
      <vxe-modal
        v-model="modalVisible"
        :title="modalTitle"
        width="500"
        :show-footer="true"
        :draggable="true"
        :esc-closable="false"
      >
        <template #default>
          <vxe-form
            :data="formData"
            :items="formItems"
            :rules="{}"
            ref="formRef"
          ></vxe-form>
        </template>
        <template #footer>
          <vxe-button @click="modalVisible = false">取消</vxe-button>
          <vxe-button status="primary" @click="saveForm">确定</vxe-button>
        </template>
      </vxe-modal>

      <!-- 右侧子表格弹窗 -->
      <vxe-modal
        v-model="rightModalVisible"
        :title="rightModalTitle"
        width="500"
        :show-footer="true"
        :draggable="true"
        :esc-closable="false"
      >
        <template #default>
          <vxe-form
            :data="rightFormData"
            :items="rightFormItems"
            :rules="{}"
            ref="rightFormRef"
          ></vxe-form>
        </template>
        <template #footer>
          <vxe-button @click="rightModalVisible = false">取消</vxe-button>
          <vxe-button status="primary" @click="saveRightForm">确定</vxe-button>
        </template>
      </vxe-modal>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import type { VxeSplitPropTypes } from "vxe-pc-ui";
import type {
  VxeGridInstance,
  VxeGridProps,
  VxeGridEvents,
  VxeGridListeners,
} from "vxe-table";
import {
  queryList,
  queryPage,
  sysDict,
  delEntityById,
  checkOnly,
  saveEntity,
} from "@/api";

interface RowVO {
  id?: number;
  type?: string;
  remarks?: string;
  label?: string;
  value?: string;
  sort?: number;
  dict_id?: string;
}

// ========== 分割面板配置 ==========
const actionConfig = reactive<VxeSplitPropTypes.ActionConfig>({
  showPrevButton: true,
  showNextButton: true,
});

// ========== 主表格（左）==========
const gridRef = ref<VxeGridInstance<RowVO>>();
const gridOptions = reactive<VxeGridProps<RowVO> & { data: RowVO[] }>({
  size: "mini",
  border: true,
   printConfig: {},
  importConfig: {},
  exportConfig: {},
  rowConfig: { isCurrent: true, isHover: true },
  checkboxConfig: { trigger: "row" },
  toolbarConfig: {
    buttons: [{ name: "新增", code: "myAdd", status: "primary" }],
    print:true,
    custom:true,
    export:true
  },
  formConfig: {
    data: { title: "" },
    items: [
      { field: "title", title: "类型", itemRender: { name: "VxeInput" } },
      {
        itemRender: {
          name: "VxeButtonGroup",
          options: [
            { type: "submit", content: "搜索", status: "primary" },
            { type: "reset", content: "重置" },
          ],
        },
      },
    ],
  },
  columns: [
    { type: "checkbox", width: 60 },
    { field: "type", title: "类型" },
    { field: "remarks", title: "描述" },
    {
      title: "操作",
      fixed: "right",
      width: 160,
      slots: { default: "operate" },
    },
  ],
  data: [],
  pagerConfig: {
    pageSize: 20,
    pageSizes: [10, 20, 50, 100],
    layouts: ["Sizes", "PrevPage", "Number", "NextPage", "FullJump", "Total"],
    total: 0,
  },
});

// ========== 子表格（右）==========
const doubleGridRef = ref<VxeGridInstance<RowVO>>();
const doubleGridOptions = reactive<VxeGridProps<RowVO> & { data: RowVO[] }>({
  size: "mini",
  border: true,
   printConfig: {},
  importConfig: {},
  exportConfig: {},
  radioConfig: { labelField: "name", trigger: "row" },
  toolbarConfig: {
    buttons: [{ name: "新增", code: "rightAdd", status: "primary" }],
    print:true,
    custom:true,
    export:true
  },
  formConfig: {
    data: { label: "", value: "" },
    items: [
      {
        field: "label",
        title: "字典项名称",
        itemRender: { name: "VxeInput", props: { placeholder: "请输入" } },
      },
      {
        itemRender: {
          name: "VxeButtonGroup",
          options: [
            { type: "submit", content: "搜索", status: "primary" },
            { type: "reset", content: "重置" },
          ],
        },
      },
    ],
  },
  columns: [
    { type: "checkbox", width: 60 },
    { field: "label", title: "字典名称" },
    { field: "value", title: "字典项值" },
    { field: "sort", title: "排序" },
    { field: "remarks", title: "备注" },
    {
      title: "操作",
      fixed: "right",
      width: 180,
      slots: { default: "operate" },
    },
  ],
  data: [],
});

// ========== 当前选中的父级 dict_id ==========
let currentParentId: string | number | null = null;

// ========== 左侧主表格弹窗相关 ==========
const modalVisible = ref(false);
const modalTitle = ref("新增");
const formData = reactive<Partial<RowVO>>({});
const isEdit = ref(false);
const options = ref();

const formItems = ref([
  {
    field: "type",
    title: "类型",
    span: 24,
    itemRender: { name: "VxeInput", props: { placeholder: "请输入" } },
  },
  {
    field: "classify",
    title: "归属",
    span: 24,
    itemRender: {
      name: "VxeSelect",
      props: { placeholder: "请输入" },
      options: [],
    },
  },
  {
    field: "remarks",
    title: "描述",
    span: 24,
    itemRender: {
      name: "VxeInput",
      props: {
        type: "textarea",
        autosize: { minRows: 2, maxRows: 4 },
        placeholder: "请输入描述",
      },
    },
  },
]);

// ========== 右侧子表格弹窗相关 ==========
const rightModalVisible = ref(false);
const rightModalTitle = ref("新增");
const rightFormData = reactive<Partial<RowVO>>({});
const isRightEdit = ref(false);

const rightFormItems = ref([
  {
    field: "label",
    title: "字典名称",
    span: 24,
    itemRender: { name: "VxeInput", props: { placeholder: "请输入字典名称" } },
  },
  {
    field: "value",
    title: "字典项值",
    span: 24,
    itemRender: { name: "VxeInput", props: { placeholder: "请输入字典项值" } },
  },
  {
    field: "sort",
    title: "排序",
    span: 24,
    itemRender: {
      name: "VxeInput",
      props: { type: "number", placeholder: "请输入排序号" },
    },
  },
  {
    field: "remarks",
    title: "备注",
    span: 24,
    itemRender: {
      name: "VxeInput",
      props: {
        type: "textarea",
        autosize: { minRows: 2, maxRows: 4 },
        placeholder: "请输入备注",
      },
    },
  },
]);

// ========== 表格勾选事件（联动右侧表格）==========
const selectChangeEvent: VxeGridEvents.CheckboxChange<RowVO> = async ({
  row,
}) => {
  if (row) {
    currentParentId = row.id;
    const result = await queryList("dictItem", { dict_id: row.id });
    doubleGridOptions.data = result || [];
  }
};

const selectAllChangeEvent: VxeGridEvents.CheckboxAll<RowVO> = () => {
  const $grid = gridRef.value;
  if ($grid) {
    const records = $grid.getCheckboxRecords();
    console.log("勾选记录:", records);
  }
};

// ========== 左侧弹窗操作 ==========
const openAddModal = async () => {
  modalTitle.value = "新增";
  isEdit.value = false;
  options.value = await sysDict({
    field: "type",
    value: "dict_model",
  });
  if (formItems.value) {
    formItems.value.forEach((item) => {
      item.itemRender.options = options.value.childList;
    });
  }
  Object.assign(formData, {
    type: "",
    remarks: "",
    classify: "",
  });
  modalVisible.value = true;
};

const handleEdit = async (row: RowVO) => {
  modalTitle.value = "编辑";
  isEdit.value = true;
  options.value = await sysDict({
    field: "type",
    value: "dict_model",
  });
  if (formItems.value) {
    formItems.value.forEach((item) => {
      item.itemRender.options = options.value.childList;
    });
  }
  Object.assign(formData, { ...row, classify: "0" });
  modalVisible.value = true;
};

const handleDelete = (row: RowVO) => {
  removeRow(String(row.id));
};

const removeRow = (ids: string) => {
  ElMessageBox.confirm(`确定要删除数据吗？`, "警告", {
    type: "warning",
  })
    .then(async () => {
      const result = await delEntityById("dict", { ids: ids });
      if (result.code == 0) {
        ElMessage.success("删除成功");
        await reloadMenuData();
      } else {
        ElMessage.error(result.message);
      }
    })
    .catch(() => {});
};

// ========== 右侧弹窗操作 ==========
const rightToolbarClick = ({ code }: { code: string }) => {
  const selected = gridRef.value?.getCheckboxRecords();
  if (!selected || selected.length === 0) {
    ElMessage.warning("请先在左侧选择一个字典类型");
    return;
  }
  currentParentId = selected[0].id;
  if (code === "rightAdd") {
    openRightAddModal(currentParentId);
  }
};

const openRightAddModal = (parentId: string | number) => {
  rightModalTitle.value = "新增";
  resetRightFormData();
  isRightEdit.value = false;
  rightFormData.dict_id = parentId;
  rightModalVisible.value = true;
};

const handleRightEdit = (row: RowVO) => {
  if (!currentParentId) {
    ElMessage.warning("请先选择左侧字典类型");
    return;
  }
  rightModalTitle.value = "编辑";
  isRightEdit.value = true;
  Object.assign(rightFormData, { ...row });
  rightModalVisible.value = true;
};

const handleRightDelete = (row: RowVO) => {
  if (!currentParentId) {
    ElMessage.warning("请先选择左侧字典类型");
    return;
  }
  ElMessageBox.confirm(`确定要删除该字典项吗？`, "警告", { type: "warning" })
    .then(async () => {
      const result = await delEntityById("dictItem", { ids: String(row.id) });
      if (result.code === 0) {
        ElMessage.success("删除成功");
        const result = await queryList("dictItem", {
          dict_id: currentParentId,
        });
        doubleGridOptions.data = result || [];
      } else {
        ElMessage.error(result.message);
      }
    })
    .catch(() => {});
};

// ========== 右侧查询逻辑 ==========
const rightFormSubmit = async ({ data }) => {
  if (!currentParentId) return;
  const result = await queryList("dictItem", {
    dict_id: currentParentId,
    ...data,
  });
  doubleGridOptions.data = result || [];
};

const rightFormReset = () => {
  doubleGridOptions.formConfig.data = { label: "", value: "" };
  rightFormSubmit({ data: {} });
};

// ========== 保存逻辑 ==========
const saveForm = async () => {
  if (!formData.id) {
    const checked = await checkOnly("dict", {
      fieldName: "type",
      fieldValue: formData.type,
    });
    if (checked.code === 0) {
      const result = await saveEntity("dict", formData);
      if (result.code == 0) {
        ElMessage.success(result.message);
      } else {
        ElMessage.error(result.message);
      }
    } else {
      ElMessage.error(checked.msg || "类型已存在");
    }
  } else {
    const result = await saveEntity("dict", formData);
    if (result.code == 0) {
      ElMessage.success(result.message);
    } else {
      ElMessage.error(result.message);
    }
  }
  Object.assign(formData, {
    type: "",
    remarks: "",
    classify: "",
    id: "",
  });
  modalVisible.value = false;
  reloadMenuData();
};

const saveRightForm = async () => {
  const { label, value } = rightFormData;
  if (!label || !value) {
    ElMessage.warning("字典名称和字典项值不能为空");
    return;
  }

  try {
    let result;
    console.log(rightFormData);
    delete rightFormData?.dict_id;
    if (!rightFormData.id) {
      result = await saveEntity("dictItem", {
        label: rightFormData.label,
        value: rightFormData.value,
        sort: rightFormData.sort,
        remarks: rightFormData.remarks,
        id: null,
        dictId: currentParentId,
      });
    } else {
      result = await saveEntity("dictItem", {
        ...rightFormData,
        dictId: currentParentId,
      });
    }

    if (result.code === 0) {
      ElMessage.success(isRightEdit.value ? "编辑成功" : "新增成功");
      resetRightFormData();
      rightModalVisible.value = false;
      const list = await queryList("dictItem", { dict_id: currentParentId });
      doubleGridOptions.data = list || [];
    } else {
      ElMessage.error(result.message);
    }
  } catch (err) {
    ElMessage.error("操作失败");
  }
};
const resetRightFormData = () => {
  Object.assign(rightFormData, {
    label: "",
    value: "",
    sort: 0,
    remarks: "",
    dict_id: null,
    id: null,
  });
  isRightEdit.value = false;
};
// ========== 数据加载 ==========
const fetchData = async (
  pageNum: number,
  pageSize: number,
  form: any
): Promise<void> => {
  try {
    const res = (await queryPage("dict", {
      pageNumber: pageNum,
      pageSize,
      ...form,
    })) as unknown as { data: RowVO[]; count: number };

    gridOptions.data = res.data || [];
    gridOptions.pagerConfig.total = res.count || 0;
  } catch (err) {
    gridOptions.data = [];
    gridOptions.pagerConfig.total = 0;
  }
};

const reloadMenuData = async (form: any = {}) => {
  const pager = gridOptions.pagerConfig;
  await fetchData(pager.currentPage || 1, pager.pageSize || 10, form);
};

// ========== 监听工具栏按钮 ==========
const gridEvents: VxeGridListeners = {
  formSubmit({ data }) {
    reloadMenuData(data);
  },
  formReset() {
    reloadMenuData();
  },
  pageChange({ currentPage, pageSize }) {
    reloadMenuData({ pageNumber: currentPage, pageSize });
  },
  toolbarButtonClick({ code }) {
    if (code === "myAdd") {
      openAddModal();
    }
  },
};

onMounted(() => {
  reloadMenuData();
});
</script>

<style scoped>
/* 可添加样式 */
</style>
